using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.VisualStudio.DebuggerVisualizers;
using TankerVisualizer;

[assembly: DebuggerVisualizer(typeof (SequenceVisualizer) /*debugger side*/,
    typeof (SequenceVisualizerObject) /*debugee side*/,
    TargetTypeName = "System.Collections.Generic.IEnumerable`1, System.Collections.IEnumerable",
    Description = "Sequence Visualizer")]

namespace TankerVisualizer
{
    public class SequenceVisualizerObject : VisualizerObjectSource
    {
        public override void GetData(object target, Stream outgoingData)
        {
            IEnumerable targetData = target as IEnumerable;
            if (targetData != null)
            {
                ArrayList dataList = new ArrayList();
                IEnumerator enumerator = targetData.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    dataList.Add(enumerator.Current);
                }

                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(outgoingData, dataList);
            }
        }
    }

    /// <summary>
    /// A Visualizer for Sequence.  
    /// </summary>
    public class SequenceVisualizer : DialogDebuggerVisualizer
    {
        protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
        {
            using (SequenceVisualizerForm sequenceVisualizerForm = new SequenceVisualizerForm(objectProvider))
            {
                windowService.ShowDialog(sequenceVisualizerForm);
            }
        }

        /// <summary>
        /// Tests the visualizer by hosting it outside of the debugger.
        /// </summary>
        /// <param name="objectToVisualize">The object to display in the visualizer.</param>
        public static void TestShowVisualizer(object objectToVisualize)
        {
            VisualizerDevelopmentHost visualizerHost = new VisualizerDevelopmentHost(objectToVisualize,
                                                                                     typeof (SequenceVisualizer),
                                                                                     typeof (SequenceVisualizerObject));
            visualizerHost.ShowVisualizer();
        }
    }
}